package com.android.basemvvm

import com.android.base_network.exception.ExceptionHandle
import com.blankj.utilcode.util.LogUtils
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.flow.onStart

object MVVMLin {

    private val defNetException = CoroutineExceptionHandler { _, throwable ->
        val exception = ExceptionHandle.handleException(throwable)
        LogUtils.e(exception)
    }

    val netException: CoroutineExceptionHandler
        get() = customNetException ?: defNetException


    private var customNetException: CoroutineExceptionHandler? = null


    fun setNetException(netException: CoroutineExceptionHandler) = apply {
        customNetException = netException
    }

}

/**
 * 绑定Loading
 */
fun <T> Flow<T>.bindLoading(model: IViewModel, text: String = "") = onStart {
    model.showLoading(text)
}.onCompletion {
    model.dismissLoading()
}